package com.kexin.common.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.kexin.common.exception.WebException;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JWTUtils {

    private  String SECRECT = "coupon-jwt";
    private  Integer expire = 2*60*60;//有效时间两个小时

    Logger logger = LoggerFactory.getLogger(JWTUtils.class);


    public  String createToken(String s) {
        return createToken(s,expire);
    }

    public String createToken(String s,Integer inputExpire){
        try {
            //构建失效时钟
            Date exipre_date = DateTime.now().plusSeconds(inputExpire).toDate();
            //创建令牌
            JWTCreator.Builder builder = JWT.create();
            //给jwt令牌playload中放入发令牌放的用户
            builder.withSubject(s);
            //设置令牌失效时间
            builder.withExpiresAt(exipre_date);
            //对令牌密钥进行加密
            Algorithm algorithm = Algorithm.HMAC256(SECRECT);
            String token = builder.sign(algorithm);
            return  token;//返回令牌
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Subject:"+s);
            throw new WebException(500,"生成token出错");
        }
    }

    public  String verifyToken(String token){
         //生成校验器
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRECT);
            //校验
            JWTVerifier build = JWT.require(algorithm).build();
            return build.verify(token).getSubject();
        } catch (Exception e) {
            logger.error("错误token:"+token);
            throw new WebException(500,"解析token出错");
        }
    }

    public static void main(String[] args) {
        JWTUtils jwtUtils = new JWTUtils();
        try {
            String token = jwtUtils.createToken("1");
            System.out.println(token);
            String oo =jwtUtils.verifyToken(token);
            System.out.println(oo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
